package com.pipayshop.service.impl;

import com.pipayshop.domain.StoreCommodityInfo;
import com.pipayshop.domain.StoreInfo;
import com.pipayshop.domain.StoreTags;
import com.pipayshop.domain.dto.ApplyShopCommodityDTO;
import com.pipayshop.domain.dto.StoreCommodityInfoDTO;
import com.pipayshop.domain.vo.*;
import com.pipayshop.entity.Image;
import com.pipayshop.mapper.PhysicalStoreCommodityInfoMapper;
import com.pipayshop.mapper.PhysicalStoreInfoMapper;
import com.pipayshop.mapper.PhysicalStoreTagsMapper;
import com.pipayshop.service.PhysicalStoreCommodityInfoService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pipayshop.exception.BusinessException;
import com.pipayshop.mapper.ImageMapper;
import com.pipayshop.utils.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Consumer;
import java.util.stream.Stream;

/**
 * <p>
 * 实体店的商品表 服务实现类
 * </p>
 *
 * @author zxb
 * @since 2023-07-27
 */
@Service
@Slf4j
public class PhysicalStoreCommodityInfoServiceImpl extends ServiceImpl<PhysicalStoreCommodityInfoMapper, StoreCommodityInfo> implements PhysicalStoreCommodityInfoService {


    @Resource
    private PhysicalStoreCommodityInfoMapper shopCommodityInfoMapper;

    @Resource
    private PhysicalStoreTagsMapper shopTagsMapper;
    @Resource
    private PhysicalStoreInfoMapper shopInfoMapper;

    @Resource
    private ImageMapper imageMapper;

    /**
     * 发布实体店商品
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean issueShopCommodity(ApplyShopCommodityDTO applyShopCommodityDTO) {
        if (applyShopCommodityDTO == null) {
            throw new BusinessException("commodity_info_empty");
        }
        ValidationUtil.validateListNotEmpty(applyShopCommodityDTO.getCommodityImgList(), "commodity_image_empty");
        ValidationUtil.validatePositiveBigDecimal(applyShopCommodityDTO.getPrice(), "commodity_price_greater_than_zero");
        ValidationUtil.validatePositiveNumber(applyShopCommodityDTO.getResidue(), "commodity_stock_non_negative");
        ValidationUtil.validatePositiveNumber(applyShopCommodityDTO.getValidityTime(), "commodity_validity_period_greater_than_zero");

        // 属性转移
        String commodityId = StringUtil.generateShortId();
        StoreCommodityInfo shopCommodityInfo = new StoreCommodityInfo(null,
                commodityId, applyShopCommodityDTO.getCommodityName(),
                applyShopCommodityDTO.getCommodityImgList().get(0),
                JSON.toJSONString(applyShopCommodityDTO.getCommodityImgList()),
                applyShopCommodityDTO.getCommodityDetail(), applyShopCommodityDTO.getPrice(),
                null, applyShopCommodityDTO.getShopId(), null, null,
                applyShopCommodityDTO.getValidityTime(), applyShopCommodityDTO.getResidue(),
                applyShopCommodityDTO.getReservationInformation(), 0,
                null, null);

        // 更新商店商品上架剩余数
        int shopIdUpdateCount = shopInfoMapper.update(null, new UpdateWrapper<StoreInfo>()
                .eq("shop_id", applyShopCommodityDTO.getShopId())
                .setSql("upload_commodity_balance = upload_commodity_balance - 1"));

        if (shopIdUpdateCount < 1) {
            log.error("store_commodity_balance_decrease_failed");
            throw new BusinessException("store_commodity_balance_decrease_failed");
        }

        // 插入商品信息
        int insertCount = shopCommodityInfoMapper.insert(shopCommodityInfo);
        if (insertCount < 1) {
            log.error("insert_commodity_info_failed");
            throw new BusinessException("insert_commodity_info_failed");
        }

        return true;
    }


    /**
     * 根据用户id查询 用户收藏的商品列表
     */
    @Override
    public PageDataVO getCollectList(Integer page, Integer limit, String userId) {
        Integer integer = shopCommodityInfoMapper.selectAllCollectProductByUserId(userId);
        List<StoreCommodityInfoVO> shopCommodityInfoVOS = shopCommodityInfoMapper.selectCollectProductByUserId((page - 1) * limit, limit, userId);
        return new PageDataVO(integer, shopCommodityInfoVOS);
    }


    /**
     * 根据用户id查询用户浏览商品历史-实体店
     */
    @Override
    public PageDataVO historyList(Integer page, Integer limit, String userId) {
        Integer integer = shopCommodityInfoMapper.selectAllHistoryProductByUserId(userId);
        List<StoreCommodityListVO> shopCommodityListVOS = shopCommodityInfoMapper.selectHistoryProductByUserId((page - 1) * limit, limit, userId);
        return new PageDataVO(integer, shopCommodityListVOS);
    }

    /**
     * 根据实体店id查询商品列表
     */
    @Override
    public List<ApplicationRecordVO> selectCommodityByUidAndStatus(String shopId) {
        return shopCommodityInfoMapper.selectCommdityListByShopIdPage(shopId);
    }


    /**
     * 根据商品id，更改商品的上下架状态
     */
    @Override
    public boolean updateCommodityStatus(String commodityId, Integer status) {
        if (!(status == 0 || status == 1)) {
            throw new BusinessException("no_permission");
        }
        int result = shopCommodityInfoMapper.update(null, new UpdateWrapper<StoreCommodityInfo>()
                .eq("commodity_id", commodityId)
                .set("status", status));
        return result > 0;
    }

    /**
     * 根据商品id，上架变为下架
     *
     * @param commodityId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCommodityUp(String commodityId) {
        int result1 = shopCommodityInfoMapper.update(null, new UpdateWrapper<StoreCommodityInfo>()
                .eq("commodity_id", commodityId)
                .set("status", 1));
        String shopId = shopCommodityInfoMapper.selectShopIdByCommodityId(commodityId);
        System.out.println(shopId);
        int result2 = shopInfoMapper.addUploadBalanceByShopId(shopId);
        if (result2 <= 0 || result1 <= 0) {
            throw new BusinessException("service_exception_contact_admin");
        }
        return true;
    }

    /**
     * 根据商品id，下架变为审核中
     *
     * @param commodityId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCommodityCheck(String commodityId) {
        int balance = shopInfoMapper.selectUploadCommodityBalanceByCommodityId(commodityId);
        if (balance <= 0) {
            throw new BusinessException("insufficient_store_product_stock");
        }
        int result = shopCommodityInfoMapper.update(null, new UpdateWrapper<StoreCommodityInfo>()
                .eq("commodity_id", commodityId)
                .set("status", 0));
        return result > 0;
    }

    @Override
    public Integer getResidueByCommodityId(String commodityId) {
        QueryWrapper wrapper = new QueryWrapper<StoreCommodityInfo>();
        wrapper.select("residue");
        wrapper.eq("commodity_id", commodityId);
        StoreCommodityInfo shopCommodityInfo = shopCommodityInfoMapper.selectOne(wrapper);
        return shopCommodityInfo.getResidue();
    }

    /**
     * 根据店铺id查找实体店商品的详情信息列表
     */
    @Override
    public List<StoreCommodityInfo1VO> selectShopInfoListByShopId(String shopId) {

        List<StoreCommodityInfo1VO> shopCommodityInfo1VOS = shopCommodityInfoMapper.selectCommodityByShopId(shopId);
        List<StoreTags> list1 = new ArrayList<>();
        for (StoreCommodityInfo1VO shopCommodityInfo1VO : shopCommodityInfo1VOS) {
            List<String> list = JSON.parseArray(shopCommodityInfo1VO.getTagList(), String.class);
            if (list == null || list.isEmpty()) {
                continue;
            }
            for (String s : list) {
                StoreTags tag_ids = shopTagsMapper.selectOne(new QueryWrapper<StoreTags>().eq("tag_id", s));
                list1.add(tag_ids);
            }
            shopCommodityInfo1VO.setShopTagsList(list1);
        }
        return shopCommodityInfo1VOS;
    }

    /**
     * 根据店铺id查找实体店商品的上架和下架列表
     */
    @Override
    public PageDataVO selectStatusListByShopId(CommodityStatusPageVO commodityStatusPageVO) {
        Page<StoreCommodityInfo> page = new Page<>(commodityStatusPageVO.getPage(), commodityStatusPageVO.getLimit());
        shopCommodityInfoMapper.selectPage(page, new QueryWrapper<StoreCommodityInfo>()
                .eq("shop_Id", commodityStatusPageVO.getShopId())
                .and(new Consumer<QueryWrapper<StoreCommodityInfo>>() {
                    @Override
                    public void accept(QueryWrapper<StoreCommodityInfo> wrapper) {
                        wrapper.eq("status", 0)
                                .or()
                                .eq("status", 1)
                                .or()
                                .eq("status", 2);
                    }
                }));
        List<StoreCommodityInfo> shopCommodityInfos = page.getRecords();
        for (StoreCommodityInfo shopCommodityInfo : shopCommodityInfos) {
            shopCommodityInfo.setAvatarImag(imageMapper.selectPath(shopCommodityInfo.getAvatarImag()));
            List<String> imageIdlist = JSON.parseArray(shopCommodityInfo.getCommodityImgList(), String.class);
            List<String> imageList = imageIdlist.stream()
                    .parallel()
                    .map(imageId -> imageMapper.selectPath(imageId))
                    .collect(Collectors.toList());
            // 将imageList数据转为字符串 ”，“号分割
//            shopCommodityInfo.setCommodityImgList(imageList.toString());
            shopCommodityInfo.setCommodityImgList(imageList.isEmpty() ? "" : String.join(",", imageList));
        }
        return new PageDataVO((int) page.getTotal(), shopCommodityInfos);
    }

    /**
     * 根据商品的id查找实体店商品的详情信息
     */
    @Override
    public StoreDetailInfoVO selectShopInfoByCommodityId(String commodityId) {
        //获取商品基本信息
        StoreDetailInfoVO shopDetailInfoVO = shopCommodityInfoMapper.selectShopInfoByCommodityId(commodityId);
        List<String> imageIdList = JSON.parseArray(shopDetailInfoVO.getCommodityImgList(), String.class);
        List<String> imageList = imageIdList.stream()
                .map(imageId -> imageMapper.selectPath(imageId))
                .collect(Collectors.toList());
        shopDetailInfoVO.setCommodityImgList1(imageList);
        shopDetailInfoVO.setCommodityImgListCode(imageIdList);
        return shopDetailInfoVO;
    }

    @Override
    public String shopCommodityTopImageUp(MultipartFile multipartFile) {
        return FileUploadUtil.allUploadImageData(multipartFile, imageMapper, FileUploadUtil.STORE_COMMODITY_TOP_IMAGE_UP, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> shopCommodityImageUp(MultipartFile[] multipartFile) {
        List<String> imageSizeList_1 = new ArrayList<>();
        List<String> imageSizeList_2 = new ArrayList<>();
        List<String> imageIdList = new ArrayList<>();
        imageSizeList_1.add(ImageConstants.SHOP_COMMODITY_IMAGE_UP_SMALL);
        imageSizeList_1.add(ImageConstants.SHOP_COMMODITY_IMAGE_UP_BIG);
        imageSizeList_2.add(ImageConstants.SHOP_COMMODITY_IMAGE_UP_BIG);
        System.out.println(multipartFile);
        for (int i = 0; i < multipartFile.length; i++) {
            if (i == 0) {

                imageIdList.add(FileUploadUtil.allUploadImageData(multipartFile[i], imageMapper, FileUploadUtil.STORE_COMMODITY_IMAGE_UP, imageSizeList_1));
            } else {

                imageIdList.add(FileUploadUtil.allUploadImageData(multipartFile[i], imageMapper, FileUploadUtil.STORE_COMMODITY_IMAGE_UP, imageSizeList_2));
            }
        }
        return imageIdList;
    }

    @Override
    public boolean updateCommodity(StoreCommodityInfoDTO shopCommodityInfoDTO) {
        ValidationUtil.validateString(shopCommodityInfoDTO.getCommodityName(),"commodity_name_required");
        ValidationUtil.validatePositiveBigDecimal(shopCommodityInfoDTO.getPrice(),"product_price_negative");
        ValidationUtil.validatePositiveNumber(shopCommodityInfoDTO.getResidue(),"commodity_stock_non_negative");
        // 商品图片列表不能为空且不能为空的图片URL
        if (shopCommodityInfoDTO.getCommodityImgList() != null) {
            for (String img : shopCommodityInfoDTO.getCommodityImgList()) {
                if (img == null || img.isEmpty()) {
                    throw new BusinessException("commodity_image_empty");
                }
            }
        }
        ValidationUtil.validateString(shopCommodityInfoDTO.getCommodityDetail(),"product_details_empty");
        if (shopCommodityInfoDTO.getDeleteImageList() != null && !shopCommodityInfoDTO.getDeleteImageList().isEmpty()) {
            if (shopInfoMapper.updateDelFlag(shopCommodityInfoDTO.getDeleteImageList()) == 0) {
                throw new BusinessException("image_usage_update_failed");
            }
        }

        // 数据验证通过，进行更新操作
        int i = shopCommodityInfoMapper.updateCommodity(shopCommodityInfoDTO);
        return i == 1;
    }

    @Override
    @Transactional
    public boolean deleteCommodity(String commodityId) {
        //删除商品前将图片缓存也删除
        List<Map<String, Object>> maps = shopCommodityInfoMapper.selectMaps(new QueryWrapper<StoreCommodityInfo>()
                .select("commodity_img_list", "avatar_imag")
                .eq("commodity_id", commodityId));

        //获取maps中所有value数据，将所有数据转化为一个字符串数组,如果是json格式，转化后将数组符合跟字符串的双引号符号去掉,并且去重
        List<String> imageIdList = maps.stream()
                .map(map -> map.values())
                .map(value -> value.toString().replaceAll("\"", "").replace("[", "").replace("]", ""))
                .flatMap(value -> Stream.of(value.split(",")))
                .map(String::trim)  // 去除空格
                .distinct()
                .collect(Collectors.toList());


        log.info("imageIdList:{}", imageIdList);

        List<String> paths = imageMapper.selectPaths(imageIdList);
        imageMapper.deleteBatchImageIds(imageIdList);

        log.info("paths:{}", paths);
        if (paths.isEmpty()) {
            return false;
        }
        // 提取相对路径
        List<String> imagePaths = paths.stream()
                .map(path -> path.replace("https://pi-pipayshop.oss-rg-china-mainland.aliyuncs.com/", ""))
                .collect(Collectors.toList());
        log.info("imagePaths:{}", imagePaths);
        OssUtil.deleteFiles(imagePaths);
        return shopCommodityInfoMapper.deleteByCommodityId(commodityId) == 1;

    }

}
